package com.cnb.telepathytalk.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.cnb.telepathytalk.R;
import com.cnb.telepathytalk.dto.SearchWordDTO;

public class SearchWordListAdapter extends BaseAdapter {
	private ArrayList<SearchWordDTO> list;
	private int layoutResId;
	private LayoutInflater inflater;
	private String genderList[];
	private String ageFromList[];
	private String ageToList[];

	public SearchWordListAdapter(Context context) {
		super();
		this.list = new ArrayList<SearchWordDTO>();
		this.layoutResId = R.layout.list_item_search_word;
		this.inflater = LayoutInflater.from(context);

		this.genderList = context.getResources().getStringArray(R.array.tele_list_gender);
		this.ageFromList = context.getResources().getStringArray(R.array.tele_list_age_from);
		this.ageToList = context.getResources().getStringArray(R.array.tele_list_age_to);
	}

	public ArrayList<SearchWordDTO> getList() {
		return list;
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public SearchWordDTO getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Holder holder = null;
		if (convertView == null) {
			convertView = inflater.inflate(layoutResId, null);
			holder = new Holder(convertView);
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
		}

		SearchWordDTO item = list.get(position);

		holder.getWord().setText(item.getSearchWord());
		holder.getGender().setText(genderList[item.getGender()]);

		int ageFrom = item.getAgeFrom() / 10;
		int ageTo = item.getAgeTo() == 0 ? 0 : (item.getAgeTo() - 1) / 10;
		holder.getAge().setText(ageFromList[ageFrom] + " ~ " + ageToList[ageTo]);

		return convertView;
	}

	private class Holder {
		private View baseView;
		private TextView word;
		private TextView gender;
		private TextView age;

		public Holder(View view) {
			super();
			baseView = view;
		}

		public TextView getWord() {
			if (word == null)
				word = (TextView) baseView.findViewById(R.id.word);
			return word;
		}

		public TextView getGender() {
			if (gender == null)
				gender = (TextView) baseView.findViewById(R.id.gender);
			return gender;
		}

		public TextView getAge() {
			if (age == null)
				age = (TextView) baseView.findViewById(R.id.age);
			return age;
		}
	}
}